package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查出所有目录
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 对目录进行分级放进children里
        // 找出根目录
        List<CategoryEntity> categoryEntities = entities.stream().filter(entry -> {
            return entry.getParentCid() == 0;
        }).map(entry -> {
            // 递归查找子目录加入
            entry.setChildren(getChildren(entry, entities));
            return entry;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return categoryEntities;
    }

    @Override
    public void removeMenusByIds(List<Long> catIds) {
        //TODO: 数据检查
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] getCategoryPath(Long catelogId) {
        List<Long> categoryPath = this.getCategoryPath(new ArrayList<>(), catelogId);
        Collections.reverse(categoryPath);
        return categoryPath.toArray(new Long[categoryPath.size()]);
    }

    private List<Long> getCategoryPath(List<Long> categoryPath, Long catelogId) {
        // 将自己装进去
        categoryPath.add(catelogId);
        // 递归查找自己的父节点
        CategoryEntity entity = this.getById(catelogId);
        Long parentCid = entity.getParentCid();
        if (parentCid != 0) {
            getCategoryPath(categoryPath, parentCid);
        }
        return categoryPath;
    }

    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> categoryEntities = all.stream().filter(entry -> root.getCatId()
                .equals(entry.getParentCid())).map(entry -> {
            // 递归查询
            entry.setChildren(getChildren(entry, all));
            return entry;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return categoryEntities;
    }

    @Cacheable(value = {"category"}, key ="#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("获取一级分类");
        return this.list(new QueryWrapper<CategoryEntity>()
                .eq("parent_cid", 0));
    }

    @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String catalogJson = ops.get("catalogJson");
        Map<String, List<Catelog2Vo>> catalogRes = null;
        if (StringUtils.isEmpty(catalogJson)) {
            // 为空,查询再返回数据
            catalogRes = this.getCatalogJsonByDbWithRedisLock();
        }else {
            // 反序列化
            System.out.println("缓存命中");
            catalogRes = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }
        // 返回
        return catalogRes;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonByDbWithRedisLock() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        // 进入后设置分布式锁, 以uuid为值方便判断唯一,
        // 设置过期时间防止服务崩溃时,锁不能释放,影响其他服务获取锁,
        // 设置锁和设置过期时间为原子操作
        String uuid = UUID.randomUUID().toString();
        Boolean lock = ops.setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        // 查询
        if (lock) {
            System.out.println("获取分布式锁成功");
            Map<String, List<Catelog2Vo>> map = null;
            try {
                synchronized (this) {
                    String json = ops.get("catalogJson");
                    if (!StringUtils.isEmpty(json)) {
                        System.out.println("缓存命中");
                        return JSON.parseObject(json, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
                    }
                    List<CategoryEntity> selectedList = this.list();
                    List<CategoryEntity> level1Categories = this.getParent_cid(selectedList, 0L);
                    map = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                        List<CategoryEntity> level2Categories = this.getParent_cid(selectedList, v.getCatId());
                        List<Catelog2Vo> catalog2List = null;
                        if (level2Categories != null) {
                            catalog2List = level2Categories.stream().map(l2 -> {
                                List<CategoryEntity> level3Categories = this.getParent_cid(selectedList, l2.getCatId());
                                List<Catelog2Vo.Catelog3Vo> catalog3List = null;
                                if (level3Categories != null) {
                                    catalog3List = level3Categories.stream()
                                            .map(l3 -> new Catelog2Vo
                                                    .Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName()))
                                            .collect(Collectors.toList());
                                }
                                return new Catelog2Vo(v.getCatId().toString(), l2.getCatId().toString(), l2.getName(), catalog3List);
                            }).collect(Collectors.toList());
                        }
                        return catalog2List;
                    }));
/*                    String catalogJson = JSON.toJSONString(map);
                    ops.set("catalogJson", catalogJson);*/
                    System.out.println("缓存未命中");
                }
            } finally {
                // 删除锁
                // 必须先判断是否是自己的,防止因为执行逻辑时间过长导致锁自动删除,然后删除其他服务的锁
                // 判断和删除必须为原子操作,否则可能出现判断间隙,锁失效引起删除其他服务的锁
                // 不管服务出现什么错误都要释放锁
                // 因此使用lua脚本,保证原子性
                String deleteScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<>(deleteScript, Integer.class), Arrays.asList("lock"), uuid);
            }
            return map;
        }else {
            System.out.println("获取分布式锁失败, 重新获取");
            // 自旋直到获取锁
            try {
                // 设置间隔防止栈溢出
                Thread.sleep(200);
            } catch (InterruptedException e) {
            }
            return this.getCatalogJsonByDbWithRedisLock();
        }
    }

    public synchronized Map<String, List<Catelog2Vo>> getCatalogJsonByDbWithLocalLock() {
        // 先查询redis中是否有,解决缓存击穿
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String json = ops.get("catalogJson");
        if (!StringUtils.isEmpty(json)) {
            System.out.println("缓存命中");
            return JSON.parseObject(json, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }
        // 获取全部
        List<CategoryEntity> selectedList = this.list();
        // 获取一级分类
        List<CategoryEntity> level1Categories = this.getParent_cid(selectedList, 0L);
        Map<String, List<Catelog2Vo>> map = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 组装二级分类集合
            List<CategoryEntity> level2Categories = this.getParent_cid(selectedList, v.getCatId());
            // 封装成 Catelog2Vo 格式
            List<Catelog2Vo> catalog2List = null;
            if (level2Categories != null) {
                catalog2List = level2Categories.stream().map(l2 -> {
                    // 组装三级分类集合
                    List<CategoryEntity> level3Categories = this.getParent_cid(selectedList, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> catalog3List = null;
                    if (level3Categories != null) {
                        catalog3List = level3Categories.stream()
                                .map(l3 -> new Catelog2Vo
                                        .Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName()))
                                .collect(Collectors.toList());
                    }
                    return new Catelog2Vo(v.getCatId().toString(), l2.getCatId().toString(), l2.getName(), catalog3List);
                }).collect(Collectors.toList());
            }
            return catalog2List;
        }));
        // 放入redis, 查询数据和放入redis是原子性操作
        String catalogJson = JSON.toJSONString(map);
        // 放入redis
        ops.set("catalogJson", catalogJson);
        System.out.println("缓存未命中");
        return map;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectedList, Long cid) {
        return selectedList.stream()
                .filter(item -> item.getParentCid().equals(cid))
                .collect(Collectors.toList());
//        return this.list(l2);
    }
}